package com.xxxy.jsq.action.term;

import com.alibaba.fastjson2.JSONObject;
import com.xxxy.jsq.dao.TermDao;
import com.xxxy.jsq.model.Page;
import com.xxxy.jsq.model.Term;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getAllTermsPageServlet")
public class getAllTermsPageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public getAllTermsPageServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，避免中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建学期模型和DAO对象
        Term model = new Term();
        TermDao dao = new TermDao();

        // 获取页面传递的查询参数
        String termFlag = request.getParameter("tflag"); // 状态参数
        String termName = request.getParameter("tname"); // 学期名称参数

        // 设置查询条件到模型
        if (termFlag != null && !termFlag.equals("")) {
            model.setTermFlag(termFlag);
        }
        if (termName != null && !termName.equals("")) {
            model.setTermName(termName);
        }

        // 获取分页参数并初始化分页对象
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("limit");
        Page page = new Page();
        if (currentPage != null && !currentPage.equals("")
                && pageSize != null && !pageSize.equals("")) {
            page.setCurrentPage(Integer.parseInt(currentPage));
            page.setCount(Integer.parseInt(pageSize));
        }

        // 调用DAO查询分页数据和总记录数
        List<Term> termList = dao.getAllDataByPage(model, page);
        int total = dao.getCount(model);

        // 构建JSON响应数据（符合LayUI表格组件要求的格式）
        JSONObject result = new JSONObject();
        result.put("code", 0); // 0表示成功（LayUI约定）
        result.put("msg", "查询成功");
        result.put("count", total); // 总记录数
        result.put("data", termList); // 分页数据列表

        // 输出JSON响应
        PrintWriter out = response.getWriter();
        out.print(result.toString());
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求与GET处理逻辑一致
        doGet(request, response);
    }
}